package com.dongdong.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dongdong.api.AddressApi;
import com.dongdong.api.CartApi;
import com.dongdong.api.ItemApi;
import com.dongdong.config.IdWorker;
import com.dongdong.mapper.TbOrderItemMapper;
import com.dongdong.mapper.TbOrderMapper;
import com.dongdong.model.*;
import com.dongdong.service.OrdersService;
import com.dongdong.utils.JwtUtil;
import com.dongdong.vo.*;
import io.jsonwebtoken.Claims;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    @Autowired
    private CartApi cartAPI;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private AddressApi addressApi;
    @Autowired
    private ItemApi itemApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @Transactional  //只能控制单体事务 控制不了分布式事务
    @GlobalTransactional  //能控制单体事务 能控制分布式事务  需要导包seata
    @Override
    public PayVO submitorder(String token, String paymentType, Long addrId) {

        // 获取购物车信息
        List<CartVO> cartList = cartAPI.getCartList(token);

        // 解析用戶信息
        Claims claims =jwtUtil.parseJwt(token);
        String subject= claims.getSubject();
        UserVO userVO = JSONObject.parseObject(subject, UserVO.class);

        //根据id获取地址信息
        TbAddress address = addressApi.selectAddrById(addrId);

        //定义存储for产生的订单和明细数据集合
         ArrayList<TbOrder> orders = new ArrayList<>();
         ArrayList<TbOrderItem> items = new ArrayList<>();
        //定义集合存储需要扣减库存的数量以及商品的id
        ArrayList<TbItem> counts = new ArrayList<>();
        long l = idWorker.nextId();
//        ArrayList<String> s = new ArrayList<>();

        //定义支付金额
        BigDecimal payMoney = new BigDecimal( 0);
        // 定义支付名称
        StringBuilder sb = new StringBuilder();


        //遍历
        for (CartVO cartVO : cartList) {
            TbOrder order = new TbOrder();
            order.setOrderId(idWorker.nextId());
            order.setPaymentType (paymentType);
            order.setStatus("1");
            order.setCreateTime(new Date());
            order.setUserId(userVO.getUsername());
            order.setReceiverAreaName (address.getAddress());
            order.setReceiverMobile (address.getMobile());
            order.setReceiver(address.getContact());
            order.setSellerId(cartVO.getSeller());
            order.setOutTradeNo(l+""); //订单编号
//            s.add(order.getOutTradeNo());//取出订单编号

            BigDecimal totalMoney = new BigDecimal( 0);
                for (DetailVO detailVO : cartVO.getDetailVOS()){
                    totalMoney = totalMoney.add(detailVO.getTotalFee());
                    payMoney = payMoney.add(detailVO.getTotalFee());
                    sb.append(detailVO.getTitle());
                    //创建订单明细
                    TbOrderItem item = new TbOrderItem();

                    item.setId(idWorker.nextId());
                    item.setItemId(detailVO.getItemId());
                    item.setGoodsId(detailVO.getGoodsId());
                    item. setOrderId(order.getOrderId());
                    item.setTitle(detailVO.getTitle());
                    item.setPrice(detailVO.getPrice());
                    item.setNum(detailVO.getNum());
                    item.setTotalFee(detailVO.getTotalFee());
                    item.setPicPath(detailVO.getPicPath());
                    item.setSellerId(order.getSellerId());
                    item.setOutTradeNo(order.getOutTradeNo()); //订单编号



                    //                tbOrderItemMapper.insertSelective(item);  //不建议这么写在for循环里
                    items.add(item);

                    //清理库存
                    TbItem tbItem = new TbItem();
                    tbItem.setId(item.getItemId());
                    tbItem.setStockCount(item.getNum());

                    counts.add(tbItem);

                }
            order.setPayment(totalMoney);

//            tbOrderMapper.insertSelective(order); //不建议这么写在for循环里
            orders.add(order);
        }

        //扣库存
        itemApi.stockCount(counts);

        //批量增加
        tbOrderMapper.insertBatch(orders);

//        int i = 1/0;  //测试是否 回滚

        tbOrderItemMapper.insertBatch(items) ;

        //清空购物车
        redisTemplate.boundHashOps(  "cartList") .delete(claims.getId()); //删缓存

        //组装支付用到的三个参数
        PayVO payVO = new PayVO();
        payVO.setOut_trade_no(l+"");
        payVO.setTotal_amount(payMoney.toString());
        payVO.setSubject(sb.toString());
        return payVO;



    }

    @Override
    public void insertaddressVO(AddressVO addressVO, String token) {
        // 解析用戶信息
        Claims claims =jwtUtil.parseJwt(token);
        String subject= claims.getSubject();
        UserVO userVO = JSONObject.parseObject(subject, UserVO.class);
        addressVO.setIsDefault("0");
        addressVO.setUserId(userVO.getUsername());

         addressApi.add(addressVO);

    }
    //修改状态
    @Transactional  //只能控制单体事务 控制不了分布式事务
//    @GlobalTransactional  //能控制单体事务 能控制分布式事务  需要导包seata
    @Override
    public void updateOrder(String outTradeNo, String tradeNo, String tradeStatus) {

//        TbOrder tbOrder = new TbOrder();
//        TbOrderItem tbOrderItem = new TbOrderItem();
        ArrayList<TbOrder> orders = new ArrayList<>();
        ArrayList<TbOrderItem> items = new ArrayList<>();

        TbOrderExample example = new TbOrderExample();
        example.createCriteria().andOutTradeNoEqualTo(outTradeNo);
        List<TbOrder> tbOrders = tbOrderMapper.selectByExample(example);

        TbOrderItemExample tbOrderItemExample = new TbOrderItemExample();
        tbOrderItemExample.createCriteria().andOutTradeNoEqualTo(outTradeNo);
        List<TbOrderItem> tbOrderItems = tbOrderItemMapper.selectByExample(tbOrderItemExample);


        for (TbOrder order : tbOrders) {
            order.setOutTradeNo(outTradeNo);
            order.setPaymentTime(new Date());  //付款时间
            order.setUpdateTime(new Date());  //修改时间
            order.setStatus("2");  //已付款

            orders.add(order);
            tbOrderMapper.updateByPrimaryKeySelective(order);  //修改订单状态

        }

        for (TbOrderItem tbOrderItem : tbOrderItems) {
            tbOrderItem.setOutTradeNo(outTradeNo);
            tbOrderItem.setTradeNo(tradeNo);
            items.add(tbOrderItem);

            tbOrderItemMapper.updateByPrimaryKeySelective(tbOrderItem);  //修改订单状态

        }
//            tbOrderMapper.updateByPrimaryKeySelective(orders);      //修改订单状态   批量修改
//            tbOrderItemMapper.updateByPrimaryKeySelective(items);  //修改订单状态   批量修改


    }

    @Override
    public List<OrderVO> selectAddressByUsername(String id) {

        TbOrderExample example = new TbOrderExample();
        example.createCriteria().andUserIdEqualTo(id).andStatusNotEqualTo("1");  //去掉未支付订单
        List<TbOrder> tbOrders = tbOrderMapper.selectByExample(example);
            List<OrderVO> orderVOList = tbOrders.stream().map((x) -> {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(x, orderVO);

                TbOrderItemExample example2 = new TbOrderItemExample();
                example2.createCriteria().andOutTradeNoEqualTo(orderVO.getOutTradeNo());   //订单号
                List<TbOrderItem> tbOrderItems = tbOrderItemMapper.selectByExample(example2);

                    List<OrderItemVO> orderItemVOS = tbOrderItems.stream().map((order) -> {
                        OrderItemVO orderItemVO = new OrderItemVO();
                        BeanUtils.copyProperties(order, orderItemVO);
                        return orderItemVO;
                    }).collect(Collectors.toList());

                orderVO.setOrderItemVOS(orderItemVOS);
                return orderVO;
            }).collect(Collectors.toList());
        return orderVOList;

    }

    @Override
    public void UpdateRefundQuery(String outTradeNo) {
        ArrayList<String> orderNo = new ArrayList<>();
        String[] numbersArray = outTradeNo.replaceAll(",$", "").split(",");
        for (String s : numbersArray) {
            orderNo.add(s);
        }
        String x = "6";
        tbOrderMapper.updateBatch(orderNo,x);
    }


}






